<?php

namespace app\api\controller\csmwj;

use addons\csmwj\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmwj\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmwj\library\xcore\xcore\utils\XcUserSessionUtils;

/**
 * APP首页的请求数据
 */
class XpmyApi extends XcmyApi //XcMyApi
{
    protected $fields = [
        "id",
        "locales",
        "name",
        "status",
        "demo",
        "cfghasdatelimit",
        "cfgbegintime",
        "cfgendtime",
        "cfgmaxanswercount",
        "cfgresultmsg",
        "cfgresultmsgimage",
        "cfghastimelimit",
        "cfgtimelimitsecs",
        "themetopnavigationtitle",
        "themebannertype",
        "themebannerstring",
        "themebannerstringstyle",
        "themebannerstringdivstyle",
        "themebannerimage",
        "themebannerimages",
        "themelogoimage",
        "themelogodivstyle",
        "themetitlefont",
        "themetitledivstyle",
        "themequestionfont",
        "themequestiondivstyle",
        "themeoptionsfontcolor",
        "themeoptionsselectedcolor",
        "themesubmitstring",
        "themesubmitdivstyle",
        "themetitleshow",
        "themequestionnoshow",
        "themewelcomefont",
        "themewelcomedivstyle",
        "themeendfont",
        "themeendedivstyle",
        "paperimage",
        "status",
        "createtime",
        "updatetime"
    ];
    protected $dictfields = ["status"];
    protected $userIdFieldName = null;
    protected $noNeedMyRight = ["paper"];

    public function xinit()
    {
        $this->model = new \app\admin\model\csmwj\Paper();
    }

    /**
     * 返回工单、用户是否完成工单、提交工单次数、当前答题的工单）
     */
    public function paper()
    {
        $id = XcRequestUtils::get("id");
        $preview = XcRequestUtils::get("preview", false, 'N');
        $userid = XcUserSessionUtils::getUserId(false);

        $paper = null;
        if (true) {
            $paper = $this->_getById($id);
            if ($preview == 'N' && $paper->status != 'normal') {
                $this->error();
            }
            $paper->cfgresultmsgimage = XcRequestUtils::cdnurl($paper->cfgresultmsgimage);
            $paper->themebannerimage = XcRequestUtils::cdnurl($paper->themebannerimage);
            $paper->themebannerimages = XcRequestUtils::cdnurls($paper->themebannerimages);
            $paper->themelogoimage = XcRequestUtils::cdnurl($paper->themelogoimage);
        }

        $questionjson = [];
        if (true) {
            $dao = new \app\admin\model\csmwj\Question();
            $questions = XcDaoUtils::getListBySql($dao, [
                ['csmwj_paper_id', '=', $id]
            ], "id,csmwj_paper_id,title,field,fieldcode,fieldtag", "weigh desc", true);
            $no = 0;
            foreach ($questions as $item) {
                $json = json_decode($item->field, true);
                $json['id'] = $item->id;
                if (isset($json['__answer__'])) {
                    $json['no'] = ++$no;
                }


                $questionjson[] = $json;
            }
        }

        $hasFinishAnswer = 'N';
        $doing_userpaper = null;
        if ($userid) {
            $userpaper =  XcDaoUtils::getRowBySql(new \app\admin\model\csmwj\Userpaper(), [
                ['csmwj_weixinuser_id', '=', $userid],
                ['csmwj_paper_id', '=', $id],
            ], null, true, false, "createtime desc");

            if ($userpaper != null && $userpaper->iseffectverison == 'Y' && $userpaper->answerstatus == 'FINISH') {
                $hasFinishAnswer = 'Y';
            } else if ($userpaper != null && $userpaper->iseffectverison == 'Y') {
                $doing_userpaper = $userpaper;
                $doing_userquestions = XcDaoUtils::getListBySql(new \app\admin\model\csmwj\Userquestion(), [
                    ['csmwj_userpaper_id', '=', $doing_userpaper->id]
                ]);
                // 装载如 question json list
                $index = 0;
                foreach ($questionjson as &$item) {
                    foreach ($doing_userquestions as $item2) {
                        if ($item['id'] == $item2->csmwj_question_id) {
                            $item['__answer__'] = json_decode($item2->answer, true);
                        }
                    }
                }
            }
        }

        $usercount = null;
        if ($userid) {
            $dao = new \app\admin\model\csmwj\Userpaper();
            $usercount = count(XcDaoUtils::getListBySql($dao, [
                ['csmwj_weixinuser_id', '=', $userid],
                ['csmwj_paper_id', '=', $id],
                ['answerstatus', '=', 'FINISH']
            ]));
        }

        $this->success('', [
            'paper' => $paper,
            'papertheme' => $this->_generateCssVarStyle($paper, ["themebannerstring", "themebannerstringstyle", "themebannerstringdivstyle"]),
            'questionjson' => $questionjson,
            'usercount' => $usercount,
            'doing_userpaper' => $doing_userpaper,
            'hasFinishAnswer' => $hasFinishAnswer,
            'userid' => $userid,
        ]);
    }

    /**
     * 重置回答工单，用于再答一次
     */
    public function resetuserpage()
    {
        $userid = XcUserSessionUtils::getUserId();
        $id = XcRequestUtils::post('id', true);

        $dao = new \app\admin\model\csmwj\Userpaper();
        $row = XcDaoUtils::getRowBySql($dao, [
            ['csmwj_weixinuser_id', '=', $userid],
            ['csmwj_paper_id', '=', $id],
            ['iseffectverison', '=', 'Y']
        ]);
        if ($row) {
            $row->save([
                'iseffectverison' => 'N',
                'updatetime' => time()
            ]);
        }

        $this->success();
    }

    /**
     * 创建回答工单，如果已经存在则直接返回
     */
    public function createuserpage()
    {
        $userid = XcUserSessionUtils::getUserId();
        $id = XcRequestUtils::post('id', true);

        $dao = new \app\admin\model\csmwj\Userpaper();
        $userpaper = XcDaoUtils::getRowBySql($dao, [
            ['csmwj_weixinuser_id', '=', $userid],
            ['csmwj_paper_id', '=', $id],
            ['iseffectverison', '=', 'Y']
        ]);

        if ($userpaper == null) {
            $userpaper = $dao->create([
                'csmwj_weixinuser_id' => $userid,
                'csmwj_paper_id' => $id,
                'iseffectverison' => 'Y',
                'createtime' => time()
            ]);
        }

        $this->success(null, [
            'userpaper' => $userpaper
        ]);
    }

    /**
     * 提交用户提交工单
     *
     * spa. 校验用户是否提交自己待回复工单
     * spb. 保存当前userpaper
     * spc. 保存userquestion
     */
    public function saveorsubmituserpaper()
    {
        $userid = XcUserSessionUtils::getUserId();
        $id = XcRequestUtils::post('id', true);
        $userpaperid = XcRequestUtils::post('userpaperid', true);
        $usedsecond = (int)XcRequestUtils::post('usedsecond', false);
        $operate = XcRequestUtils::post('operate', true); // submit/save/forcesubmit
        $values = XcRequestUtils::requestJsonBody('values', true);

        // spb
        if (true) {
            $statdate = date('Y-m-d', time());

            $score = $this->_calcScore($id, $values);
            $dao = new \app\admin\model\csmwj\Userpaper();
            if ($operate == 'submit') {
                $row2 = XcDaoUtils::getRowById($dao, $userpaperid);
                $row2->save([
                    'iseffectverison' => 'Y',
                    'image'=>input('image') ?? '',
                    'answerstatus' => 'FINISH',
                    'submitmethod' => 'MT',
                    'usedsecond' => $usedsecond,
                    'updatetime' => time(),
                    'statdate' => $statdate,
                    'ip' => $this->request->ip(),
                    'score' => $score
                ]);
            } else if ($operate == 'forcesubmit') {
                $row2 = XcDaoUtils::getRowById($dao, $userpaperid);
                $row2->save([
                    'iseffectverison' => 'Y',
                    'image'=>input('image') ?? '',
                    'answerstatus' => 'FINISH',
                    'submitmethod' => 'AT8TIME',
                    'usedsecond' => $usedsecond,
                    'updatetime' => time(),
                    'statdate' => $statdate,
                    'ip' => $this->request->ip(),
                    'score' => $score
                ]);
            } else {
                $row2 = XcDaoUtils::getRowById($dao, $userpaperid);
                $row2->save([
                    'iseffectverison' => 'N',
                    'image'=>input('image') ?? '',
                    'answerstatus' => 'DRAFT',
                    'usedsecond' => $usedsecond,
                    'updatetime' => time(),
                    'statdate' => $statdate,
                    'ip' => $this->request->ip(),
                    'score' => $score
                ]);
            }
        }
        // spc
        if (true) {
            $dao = new \app\admin\model\csmwj\Userquestion();

            foreach ($values as $item) {
                if (isset($item['__answer__'])) {
                    $row = XcDaoUtils::getRowBySql($dao, [
                        ['csmwj_userpaper_id', '=', $userpaperid],
                        ['csmwj_question_id', '=', $item['id']]
                    ]);
                    if ($row) {
                        $row2 = XcDaoUtils::getRowById($dao, $row->id);
                        $row2->save([
                            'answer' => json_encode($item['__answer__']),
                            'updatetime' => time()
                        ]);
                    } else {
                        $dao->create([
                            'csmwj_userpaper_id' => $userpaperid,
                            'csmwj_question_id' => $item['id'],
                            'answer' => json_encode($item['__answer__']),
                            'createtime' => time()
                        ]);
                    }
                }
            }
        }
        $this->success();
    }


    /**
     * 计算工单实际得分
     * TODO Test
     */
    private function _calcScore($paperid, $values)
    {
        $score = null;

        $questions = XcDaoUtils::getListBySql(new \app\admin\model\csmwj\Question(), [
            ['csmwj_paper_id', '=', $paperid]
        ]);

        // 匹配答案
        $score = 0;
        foreach ($questions as $question) {
            // 获取用户提交的答案
            $useranswers = [];
            foreach ($values as $value) {
                if ($question->id == $value['id']) {
                    switch ($question->csmtype) {
                        case 'question-radio-group':
                            $useranswers[] = $value['__answer__']['value'];
                            break;
                        case 'question-checkbox-group':
                            foreach ($value['__answer__'] as $item2) {
                                $useranswers[] = $item2;
                            }
                            break;
                    }
                }
            }

            // 与答案比较
            $questionjson = json_decode($question->field, true);
            if (isset($questionjson['csmwjshowscore']) && $questionjson['csmwjshowscore']['value'] === true) {
                // 要根据json来判定,怎么是答案
                switch ($questionjson['csmwjshowscore']['method']) {
                    case 'oneanswer':
                        $answer = $questionjson['csmwjshowscore']['oneanswer']['answer'];
                        if (count($useranswers) == 1 && $useranswers[0] == $answer) {
                            $score = $score + $questionjson['csmwjshowscore']['oneanswer']['score'];
                        }
                        break;
                    case 'everyscore':
                        foreach ($useranswers as $useranswer) {
                            foreach ($questionjson['csmwjoptions']['options'] as $option) {
                                if ($useranswer == $option['value']) {
                                    $score = $score + $option['score'];
                                }
                            }
                        }
                        break;
                }
            }
        }

        return $score;
    }



    /**
     * 生成css style的变量赋值
     *
     * @param [type] $paper 数据库paper对象model
     * @param [type] $keyarr ["themebannerstring","themebannerstringstyle"]
     * @return void
     *      --themebannerstring-font-size:12px;--themebannerstring-color:#00ff00
     */
    private function _generateCssVarStyle($paper, $keyarr)
    {
        if ($paper == null) {
            return null;
        }
        $sr = "";
        foreach ($keyarr as $v) {
            $modelvalue = $paper->$v;
            if ($modelvalue != null && $modelvalue != '') {
                $varr = json_decode($modelvalue);
                if ($varr != null) {
                    foreach ($varr as $kk => $vv) {
                        $sr .= "--{$v}-{$kk}:{$vv};";
                    }
                }
            }
        }
        return $sr;
    }
}
